package com.chixing.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;


public class MsgUtil {
    public static int sendMsg(String moilePhone, String code) {
        String accessKeyId = "LTAI4Fy3EXqrJAnZxka3uH7e";
        String accessSecret = "WJ5sy4Ckl901HmBnvLFBuVjymeI1FJ";

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", moilePhone);
        request.putQueryParameter("SignName", "向家网");
        request.putQueryParameter("TemplateCode", "SMS_204106827");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);

            // 返回
            String result = response.getData();
            System.out.println(response.getData());

            // 转json
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            // 请求成功
            if ("OK".equals(jsonObject.getString("Code"))) {
                return 0;
            } else {
                // 失败
                return 1;
            }

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return 1;
    }
}
